<script setup>
import 'leaflet-draw/dist/leaflet.draw.css'
import '@supermap/iclient-leaflet/css/index'

import L from 'leaflet'
import '@supermap/iclient-leaflet'
import 'leaflet-draw'

import { provide } from 'vue'
import { CanvasLabel } from "@panzhiyue/leaflet-canvaslabel"

const activeIndex = '1'
</script>

<template>
  <el-container class="container">
    <el-header class="header">
      <el-menu :default-active="activeIndex" @select="handleSelect" mode="horizontal" background-color="#6093c5" text-color="#ffffff" active-text-color="#ffd04b">
        <img style="width: 180px" src="/logo.svg" alt="SuperMap iClient Logo" />
        <el-menu-item index="1" class="menuItem">地图叠加</el-menu-item>
        <el-menu-item index="2" class="menuItem">影像服务</el-menu-item>
        <el-menu-item index="3" class="menuItem">地物查询定位</el-menu-item>
        <el-menu-item index="4" class="menuItem">矢量瓦片</el-menu-item>
        <el-sub-menu index="5">
          <template #title>
            <p class="menuItem">可视化</p>
          </template>
          <el-menu-item index="5-1" class="menuItem">聚点图</el-menu-item>
          <el-menu-item index="5-2" class="menuItem">迁徙图</el-menu-item>
        </el-sub-menu>
        <el-menu-item index="6" class="menuItem">地图量算</el-menu-item>
        <el-menu-item index="7" class="menuItem">Web 打印</el-menu-item>
        <el-sub-menu index="8">
          <template #title>
            <p class="menuItem">交通网络分析</p>
          </template>
          <el-menu-item index="8-1" class="menuItem">最佳路径分析</el-menu-item>
          <el-menu-item index="8-2" class="menuItem">爆管分析</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-header>

    <el-main class="main">
      <router-view></router-view>
      <div id="map"></div>
      <div id="mapBaseInfo">
        <p id="mouseLatlng"></p>
      </div>
    </el-main>

    <el-footer class="footer">
      WebGIS 高级认证 Demo - 支持中心 - 支持二部 - 刘程贤
    </el-footer>
  </el-container>
</template>

<script>
export default {
  name: 'Main',
  data() {
    return {
      CRS_4490: undefined,
      restMapUrl: `${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/map-dy/rest/maps/dy`,
      restLayer: undefined,
      restDataUrl: `${this.$store.state.iserver.protocol}://${this.$store.state.iserver.hostname}:${this.$store.state.iserver.port}/iserver/services/data-dy/rest/data`,
      datasourceName: 'dy',
      datasetName: 'POI',
      map: undefined,
      drawControl: undefined,
      editableLayers: undefined
    };
  },
  mounted() {
    // 初始化地图控件
    this.map = new L.map('map', {
      center: [31.12, 104.48],
      maxZoom: 17,
      minZoom: 0,
      zoom: 4,
      renderer: new L.CanvasLabel({
        collisionFlg: false
      })
    });

    this.map.on("mousemove", this.updateMouseLatLngPosition);

    // 不知为何，部分 Layer 移除时没有清除绑定的事件，会导致图层异常
    // 在 Layer 移除事件中手动清除多余（未清理干净）的事件
    this.map.on('layerremove', layerEvent => {
      var events = this.map._events;
      for (const key in events) {
        if (Object.hasOwnProperty.call(events, key)) {
          const subEvents = events[key];
          for (const subKey in subEvents) {
            if (Object.hasOwnProperty.call(subEvents, subKey)) {
              const event = subEvents[subKey];
              if (event.ctx !== undefined && event.ctx._leaflet_id === layerEvent.layer._leaflet_id) {
                subEvents.splice(parseInt(subKey), 1);
              }
            }
          }
        }
      }
    });

    // 比例尺控件
    var scaleControl = new L.control.scale();
    scaleControl.addTo(this.map);

    // 绘制控件
    this.editableLayers = new L.FeatureGroup();
    this.map.addLayer(this.editableLayers);
    this.drawControl = new L.Control.Draw({
      position: 'topright',
      draw: {
        polyline: {
          icon: new L.DivIcon({
            iconSize: new L.Point(8, 8),
            className: 'leaflet-div-icon leaflet-editing-icon'
          }),
        },
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false,
        circlemarker: false
      },
      edit: {
        featureGroup: this.editableLayers,
        edit: false,
        remove: true
      }
    });

    provide('map', this.map);
    provide('drawControl', this.drawControl);
    provide('editableLayers', this.editableLayers);

    this.$router.push({ path: "/" });
  },
  methods: {
    // 更新鼠标当前位置和经纬度信息
    updateMouseLatLngPosition(e) {
      var position = L.CRS.EPSG3857.project(e.latlng);
      L.DomUtil.get("mouseLatlng").innerHTML = `【X: ${position.x.toFixed(
        4
      )} Y: ${position.y.toFixed(4)}】 【经度: ${e.latlng.lng.toFixed(
        4
      )}° 纬度: ${e.latlng.lat.toFixed(4)}°】`;
    },

    // 菜单选中事件
    handleSelect(index) {
      var currentPath = window.location.pathname;
      var clickedPath = '/';
      switch (index) {
        case '1':
          clickedPath = "/";
          break;
        case '2':
          clickedPath = "/imageservice";
          break;
        case '3':
          clickedPath = "/fgbsearchlocation";
          break;
        case '4':
          clickedPath = "/vectortile";
          break;
        case '5-1':
          clickedPath = "/markercluster";
          break;
        case '5-2':
          clickedPath = "/migration";
          break;
        case '6':
          clickedPath = "/measurement";
          break;
        case '7':
          clickedPath = "/webprint";
          break;
        case '8-1':
          clickedPath = "/bestpathanalyst";
          break;
        case '8-2':
          clickedPath = "/burstanalyst";
          break;
      }

      if (clickedPath !== currentPath) {
        // 清空 map 中已存在的图层
        if (this.map !== undefined) {
          this.map.off('click');
          this.map.off(L.Draw.Event.CREATED);
          this.map.off(L.Draw.Event.DRAWVERTEX);
          this.map.off(L.Draw.Event.DELETED);
          this.map.off(L.Draw.Event.DRAWSTOP);

          this.map.eachLayer(function (layer) {
            var events = layer._map._events;
            for (const key in events) {
              if (Object.hasOwnProperty.call(events, key)) {
                const subEvents = events[key];
                for (const subKey in subEvents) {
                  if (Object.hasOwnProperty.call(subEvents, subKey)) {
                    const event = subEvents[subKey];
                    if (event.ctx !== undefined && event.ctx._leaflet_id === layer._leaflet_id) {
                      subEvents.splice(parseInt(subKey), 1);
                    }
                  }
                }
              }
            }
            layer.remove();
          });

          this.editableLayers.clearLayers();
          this.drawControl.remove();
        }
      }

      this.$router.push({ path: clickedPath });
    }
  }
}
</script>

<style scoped>
.container {
  height: 100%;
  width: 100%;
}

.header {
  max-height: 80px;
  width: 100%;
  padding: 0px;
}

.main {
  line-height: calc(100vh - 81px);
  width: 100%;
  padding: 0px;
}

.footer {
  background-color: #6093c5;
  color: #ffffff;
  width: 100%;
  font-size: 14px;
  font-weight: 300;
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  --el-footer-padding: 0px;
  --el-footer-height: 20px;
}

.menuItem {
  font-size: large;
  font-weight: 600;
  font-family: "Avenir", Helvetica, Arial, sans-serif;
}

#map {
  width: 100%;
  height: calc(100vh - 81px);
  float: left;
}

#mapBaseInfo {
  float: left;
  position: absolute;
  z-index: 999;
  line-height: 20px;
  bottom: 0px;
  right: 0px;
}

#mouseLatlng {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  text-align: left;
  color: #ffffff;
  margin: 0;
  font-size: 13px;
}
</style>